package cn.hongwei.nacos.handler.servicelist;

import cn.hongwei.nacos.annotation.Handler;
import cn.hongwei.nacos.constant.RequestConstants;
import cn.hongwei.nacos.context.InstanceContext;
import cn.hongwei.nacos.dto.Namespace;
import cn.hongwei.nacos.dto.WebServiceListDto;
import cn.hongwei.nacos.dto.WebServices;
import cn.hongwei.nacos.handler.base.InstanceBaseHandler;
import cn.hongwei.nacos.param.NacosServicesListParam;
import okhttp3.Call;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author Great
 * @email 1224028994@qq.com
 * 服务列表handler
 * 这里构建最终的请求参数了 双层map
 */
@Handler
public class ServiceListHandler extends InstanceBaseHandler {


    @Override
    public void doHandler(InstanceContext instanceContext) {
        //获取本次请求的参数
        NacosServicesListParam nacosServicesListParam = instanceContext.getInstanceRequest().getNacosServicesListParam();
        List<Namespace> namespaces = nacosServicesListParam.getNamespaceDto().getData();
        //所有服务列表
        List<WebServiceListDto> serviceResult = new ArrayList<>();
        //构建最终的请求参数
        Map<String, Map<String, List<String>>> instancesParam = new HashMap<>();
        for (Namespace namespace : namespaces) {
            int pageNo = 1;
            try {
                //uri /nacos/v1/ns/catalog/services
                Request request = new Request.Builder()
                        .get()
                        .url(RequestConstants.PROTOCOL_PREFIX + nacosServicesListParam.getIp() + RequestConstants.MARK_COLON + nacosServicesListParam.getPort() +
                                RequestConstants.WEB_SERVICE_LIST_PATH + RequestConstants.MARK_QUESTION +
                                RequestConstants.NAMESPACE_ID + namespace.getNamespace() +//namespaceId
                                RequestConstants.REQUEST_SUFFIX_PARAM + RequestConstants.PAGE_NO + pageNo + //pageNo
                                RequestConstants.REQUEST_SUFFIX_PARAM + RequestConstants.PAGE_SIZE + RequestConstants.PAGE_SIZES) //pageSize
                        .build();
                Call call = okHttpClient.newCall(request);
                Response response = call.execute();
                ResponseBody body = response.body();
                String string = body.string();
                //TODO...没有做分页逻辑处理
                WebServiceListDto webServiceListDto = objectMapper.readValue(string, WebServiceListDto.class);
                webServiceListDto.setCount(webServiceListDto.getServiceList().size());
                serviceResult.add(webServiceListDto);

                //组名和服务名map
                Map<String, List<String>> groupAndName = new HashMap<>();
                List<WebServices> serviceList = webServiceListDto.getServiceList();
                Map<String, List<WebServices>> collect = serviceList.parallelStream().collect(Collectors.groupingBy(WebServices::getGroupName));
                Set<String> keys = collect.keySet();
                for (String key : keys) {
                    List<WebServices> webServices = collect.get(key);
                    List<String> names = webServices.stream().map(WebServices::getName).collect(Collectors.toList());
                    groupAndName.put(key, names);
                }
                //将当前名称空间下组名和服务名保存到map中
                instancesParam.put(namespace.getNamespace(), groupAndName);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }

        //设置到响应中
        instanceContext.getInstanceResponse().setWebServiceListDtos(serviceResult);
        //设置最终请求参数
        instanceContext.getInstanceRequest().setInstancesParam(instancesParam);

        doNextHandler(instanceContext);
    }
}
